/**
 * Created by GUO on 2017/5/20.
 * @flow
 * 文章列表
 */

import React from 'react';
import {
    FlatList,
    View,
    ActivityIndicator,
    StyleSheet,
    Text,
} from 'react-native';
import PostItem,{ITEM_HEIGHT} from './PostItem';
import HttpClient from '../HttpClient';

type Props = {
    url: string,
    lang?: string,
    cid?: string,
    initLoad: boolean,
    onPressItem?:(item:Object) => void
}

export default class PostsList extends React.PureComponent{

    props: Props;

    static defaultProps = {
        lang: '-1',
        cid: '0',
    };


    state = {
        posts:[],
        fetching: true,
        refreshing: false,
        pn:0,
        hasNext: false,
        loading: false,
        loaded: false,
    };

    constructor(props:Props){
        super(props);
        this.state.loaded = props.initLoad;
    }

    get lastId(): ?string{
        let { posts } = this.state;
        return posts.length > 0 ? posts[posts.length -1].id : null;
    }

    _fetchData(refresh: boolean = false){

        let params: Object = {
            size: 30,
            lang: this.props.lang,
            cid: this.props.cid,
            is_pad: 1,
        };
        if(!refresh){
            Object.assign(params,{pn:this.state.pn});
            if(this.lastId){
                Object.assign(params,{last_id:this.lastId});
            }
        }

        HttpClient.get(this.props.url,{params}).then(response => {

            console.log(response.data);

            let { posts } = this.state;
            let { articles,pn,has_next, } = response.data;

            if(refresh){
                posts = [...articles];
            }else{
                posts = posts.concat(articles);
            }
            this.setState({
                fetching:false,
                refreshing:false,
                loading: false,
                posts,
                hasNext: has_next,
                pn: pn +1
            });

        }).catch(e => {
            this.setState({
                fetching:false
            });
            console.log('=err====>>',e);
        });
    }

    componentDidMount(){
        this.props.initLoad && this._fetchData();
    }

    //只加载一次
    fetchDataIfNeed(){
        if(!this.state.loaded){
            this.setState({loaded:true},()=>this._fetchData());
        }
    }

    render(){
        if(this.state.fetching){
            return <ActivityIndicator/>
        }else if(this.state.posts.length > 0){
            return <FlatList
                style = {styles.list}
                data={this.state.posts}
                renderItem = {this._renderItem.bind(this)}
                keyExtractor = {(item,index) => item.id}
                getItemLayout = {this._getItemLayout.bind(this)}
                ListFooterComponent = {this._renderFooter.bind(this)}
                refreshing={this.state.refreshing}
                onRefresh = {()=> this.setState({refreshing:true},()=>this._fetchData(true))}
                onEndReachedThreshold = {0.2}
                onEndReached = {this._onEndReached.bind(this)}
            />;
        }else{
            return <Text>数据为空／超时</Text>
        };
    }

    _getItemLayout(data,index){
        return {length:ITEM_HEIGHT+4,offset:(ITEM_HEIGHT+4+(index==0?8:0))*index,index};
    }

    _renderItem({item,index}){
        return (
            <PostItem
                onPress={()=> this._onPressItem(item)}
                post={item}
                style={{marginTop:index == 0?8:0}}/>
        );
    }

    _onPressItem(item){
        this.props.onPressItem && this.props.onPressItem(item);
    }

    _renderFooter(){
        if(this.state.hasNext){
         return <ActivityIndicator style={{height:48}}/>
        }
        return null;
    }

    _onEndReached({ distanceFromEnd }){
        if(!this.state.loading && this.state.hasNext){
            this.setState({loading:true},this._fetchData);
        }
    }

}
const styles = StyleSheet.create({
    list:{
        // backgroundColor:'#F2F4F7',
    }
});